package config

import (
	"fmt"
	"os"

	"gopkg.in/yaml.v3"
)

type Config struct {
	System SystemConfig `yaml:"system"`
	Mysql  MysqlConfig  `yaml:"mysql"`
	Redis  RedisConfig  `yaml:"redis"`
	Jwt    JwtConfig    `yaml:"jwt"`
	Upload UploadConfig `yaml:"upload"`
}

type SystemConfig struct {
	Port         int    `yaml:"port"`
	Env          string `yaml:"env"`
	Log_level    string `yaml:"log_level"`
	Log_file     string `yaml:"log_file"`
	Log_max_size int    `yaml:"log_max_size"`
	Log_max_age  int    `yaml:"log_max_age"`
}
type MysqlConfig struct {
	Host     string `yaml:"host"`
	Port     int    `yaml:"port"`
	Username string `yaml:"username"`
	Password string `yaml:"password"`
	Database string `yaml:"database"`
}

type RedisConfig struct {
	Host     string `yaml:"host"`
	Port     int    `yaml:"port"`
	Password string `yaml:"password"`
}

type JwtConfig struct {
	Secret    string `yaml:"secret"`
	ExpiresAt string `yaml:"expires_at"`
}

type UploadConfig struct {
	Path     string `yaml:"path"`
	Max_size int    `yaml:"max_size"`
	Max_age  int    `yaml:"max_age"`
}

func LoadConfig(path string) (*Config, error) {
	var config Config

	yamlFile, err := os.ReadFile(path)
	if err != nil {
		return nil, err
	}

	err = yaml.Unmarshal(yamlFile, &config)
	if err != nil {
		return nil, err
	}

	return &config, nil
}

// 获取mysql的dsn
func (sql MysqlConfig) DSN() string {
	return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", sql.Username, sql.Password, sql.Host, sql.Port, sql.Database)
}

// 获取redis的连接字符串
func (redis RedisConfig) DSN() string {
	return fmt.Sprintf("%s:%d", redis.Host, redis.Port)
}
